package com.acme.bankapp.server;

import com.acme.bankapp.domain.bank.Bank;
import com.sun.org.apache.bcel.internal.generic.BREAKPOINT;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Alfeya
 * Date: 30.11.14
 * Time: 23:16
 * To change this template use File | Settings | File Templates.
 */
public class BankServer {
    public void startServer(Bank bank) {
        int port = 9999;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        while(true) {
            try {
                System.out.println("Begin listening port " + port);
                Socket socket;
                socket = serverSocket.accept();

                DataInputStream dis = new DataInputStream(socket.getInputStream());
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                System.out.println("New user begin connection");

                String cmd = "";
                do {
                    cmd = dis.readUTF().toLowerCase(); //read from client
                    switch (cmd) {
                        case "request":
                            dos.writeUTF("response");
                            break;
                        case "exit":
                            dos.writeUTF("exit");
                            break;
                        default:
                            System.out.println("Incorrect command");
                            break;
                    }
                }
                while (!cmd.equals("exit"));
                socket.close();
            } catch (IOException e) {
                System.out.println("Client has been disconnected. Server is waiting for a new connection");
                //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
}
